package com.shangyitong.yygh_hosp.service.impl.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.shangyitong.ResultCodeEnum;
import com.shangyitong.exception.HospitalException;
import com.shangyitong.util.MapToJavaObjectWithClass;
import com.shangyitong.yygh.model.hosp.*;
import com.shangyitong.yygh.vo.hosp.BookingScheduleRuleVo;
import com.shangyitong.yygh_hosp.mapper.HospitalSetMapper;
import com.shangyitong.yygh_hosp.repository.DepartmentRepository;
import com.shangyitong.yygh_hosp.repository.HospitalRepository;
import com.shangyitong.yygh_hosp.repository.HospitalScheduleRepository;
import com.shangyitong.yygh_hosp.service.ScheduleService;
import com.shangyitong.yygh_hosp.service.api.HospitalScheduleService;
import com.shangyitong.yygh_hosp.service.impl.ScheduleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class HospitalScheduleServiceImpl implements HospitalScheduleService {
    @Autowired
    private HospitalScheduleRepository hospitalScheduleRepository;
    @Autowired
    private HospitalSetMapper hospitalSetMapper;
    @Autowired
    private DepartmentRepository departmentRepository;
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private ScheduleService scheduleService;


    @Override
    public void saveSchedule(Map<String, String[]> parameterMap) {
        Schedule schedule = JSONObject.parseObject(MapToJavaObjectWithClass.mapToJavaObject(parameterMap), Schedule.class);
        String hoscode = schedule.getHoscode();
        String depcode = schedule.getDepcode();
        if (StringUtils.isEmpty(hoscode) || StringUtils.isEmpty(depcode)) {
            throw new HospitalException(ResultCodeEnum.PARAM_ERROR);
        } else {
            HospitalSet hospitalSet = hospitalSetMapper.getByHoscode(hoscode);
            Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
            if (hospitalSet != null && hospital != null) {
                Department department = departmentRepository.getByHoscodeAndDepcode(hoscode, depcode);
                if (department != null) {
                    hospitalScheduleRepository.save(schedule);
                } else {
                    throw new HospitalException(ResultCodeEnum.DEPARTMENT_NOT_EXIST);
                }
            } else {
                throw new HospitalException(ResultCodeEnum.HOSPITAL_OPEN);
            }
        }
    }

    @Override
    public Page<Schedule> showSchedule(Map<String, String[]> parameterMap) {
        String hoscode = (String) MapToJavaObjectWithClass.switchObjectMap(parameterMap).get("hoscode");
        HospitalSet hospitalSet = hospitalSetMapper.getByHoscode(hoscode);
        if (hospitalSet == null) {
            throw new HospitalException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        int pageNum = Integer.parseInt((String) MapToJavaObjectWithClass.switchObjectMap(parameterMap)
                .get("page"));
        int pageSize = Integer.parseInt((String) MapToJavaObjectWithClass.switchObjectMap(parameterMap)
                .get("limit"));
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize);
        Page<Schedule> schedulePage = hospitalScheduleRepository.findByHoscode(hoscode, pageable);
        return schedulePage;
    }

    @Override
    public void removeSchedule(Map<String, String[]> parameterMap) {
        Schedule schedule = JSONObject.parseObject(MapToJavaObjectWithClass.mapToJavaObject(parameterMap), Schedule.class);
        String hoscode = schedule.getHoscode();
        String hosScheduleId = schedule.getHosScheduleId();
        if (StringUtils.isEmpty(hoscode) || StringUtils.isEmpty(hosScheduleId)) {
            throw new HospitalException(ResultCodeEnum.DATA_ISNULL);
        }
        Schedule scheduleExist = hospitalScheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (scheduleExist != null) {
            hospitalScheduleRepository.deleteById(scheduleExist.getId());
        } else {
            throw new HospitalException(ResultCodeEnum.DATA_ISNULL);
        }
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(Integer page, Integer limit, String hoscode, String depcode) {
        Map<String, Object> finalResult = new HashMap<>();
        Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);
        if (null == hospital) {
            throw new HospitalException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        IPage<Date> iPage = getListDate(page, limit, bookingRule);
        List<Date> dateList = iPage.getRecords();
        //获取可预约日期科室剩余预约数
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(dateList);
        Aggregation agg = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")         //分组字段
                        .first("workDate").as("workDate")
                        .count().as("docCount")
                        .sum("availableNumber").as("availableNumber")
                        .sum("reservedNumber").as("reservedNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregationResults = mongoTemplate.aggregate(agg, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> scheduleVoList = aggregationResults.getMappedResults();
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(scheduleVoList)) {
            scheduleVoMap = scheduleVoList.stream().collect(Collectors.toMap(BookingScheduleRuleVo::getWorkDate,
                            BookingScheduleRuleVo -> BookingScheduleRuleVo));
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for (int i = 0, len = dateList.size(); i < len; i++) {
            Date date = dateList.get(i);
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            if (null == bookingScheduleRuleVo) { // 说明当天没有排班医生
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            //计算当前预约日期为周几
            String dayOfWeek = ScheduleServiceImpl.getDayOfWeek(new DateTime(date));
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if (i == len - 1 && page == iPage.getPages()) {
                bookingScheduleRuleVo.setStatus(1);
            } else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间,不能预约
            if (i == 0 && page == 1) {
                DateTime stopTime = getDateTime(new Date(), bookingRule.getStopTime());
                if (stopTime.isBeforeNow()) {
                    //停止预约
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        finalResult.put("bookingScheduleList", bookingScheduleRuleVoList);
        finalResult.put("total", iPage.getTotal());
        //其他基础数据
        Map<String, Object> baseMap = new HashMap<>();
        //医院名称
        baseMap.put("hosname", hospital.getHosname());
        //科室
        Department department = departmentRepository.getByHoscodeAndDepcode(hoscode, depcode);
        //大科室名称
        baseMap.put("bigname", department.getBigname());
        //科室名称
        baseMap.put("depname", department.getDepname());
        //月
        baseMap.put("workDateString", new DateTime().toString("yyyy年MM月"));
        //放号时间
        baseMap.put("releaseTime", bookingRule.getReleaseTime());
        //停号时间
        baseMap.put("stopTime", bookingRule.getStopTime());
        finalResult.put("baseMap", baseMap);
        return finalResult;
    }

    private IPage<Date> getListDate(Integer page, Integer limit, BookingRule bookingRule) {
        DateTime dateTime = getDateTime(new Date(), bookingRule.getReleaseTime());
        Integer cycle = bookingRule.getCycle();
        //如果当前日期已过预约日期，则预约周期最后一天为放号时间，周期加1
        if (dateTime.isBeforeNow()) {
            cycle += 1;
        }
        //可预约的所有日期，最后一天显示即将放好倒计时
        List<Date> dateList = new ArrayList<>();
        for (int i = 0; i < cycle; i++) {
            //计算当前预约日期
            DateTime curDateTime = new DateTime().plusDays(i);
            String dateString = curDateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //对日期进行分页或者当页显示，如果end大于所有预约日期，则当页显示，如果end<所有预约日期，则分页显示
        List<Date> pageDateList = new ArrayList<>();
        int start = (page - 1) * limit;
        int end = (page - 1) * limit + limit;
        if (end >= dateList.size()) {
            end = dateList.size();
        }
        for (int i = start; i < end; i++) {
            pageDateList.add(dateList.get(i));
        }
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, 7, dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }


    public static DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " " + timeString;
        return DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
    }

    @Override
    public List<Schedule> findScheduleList(String hoscode, String depcode, String workDate) {
        return scheduleService.getScheduleDetail(hoscode, depcode, workDate);
    }

    @Override
    public Schedule getSchedule(String scheduleId) {
        Schedule schedule = hospitalScheduleRepository.getById(scheduleId);
        Hospital hospital = hospitalRepository.getHospitalByHoscode(schedule.getHoscode());
        if (hospital == null) {
            throw new HospitalException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        schedule.getParam().put("hosname", hospital.getHosname());
        schedule.getParam().put("depname",
                departmentRepository.getByHoscodeAndDepcode(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        schedule.getParam().put("dayOfWeek", ScheduleServiceImpl.getDayOfWeek(new DateTime(schedule.getWorkDate())));
        return schedule;
    }
}
